import Uploader from 'packages/BaseUpload/uploader';
import { sendSingleMessage } from '@src/modules/system/frame/component/InternalCoordination/chat/components/send.js';

const MAX_SIZE = 50 * 1024 * 1024
export default {
  name: 'file-mixin',
  inject:['chatParams'],
  data() {
    return {
    }
  },
  methods: {
    validate(file) {
      let fileName = file.name
      // 验证文件大小
      if (file.size > MAX_SIZE) return this.$t('common.base.uploadModal.fileSizeLowerTips', {size: '50m'})
      // 验证是否有扩展名
      let lastDotIndex = fileName.lastIndexOf('.')
      if (lastDotIndex < 0) return this.$t('common.base.uploadModal.unkonowFileType')
    },

    async handleFileChange(event, messageType) {
      let files = event.target.files
      if (files.length > 9) {
        return this.$message.error(this.$t('common.base.uploadModal.uploadCountTips', {count: '9'}))
      }
      if (files.length == 0) return
      let count = 0
      let loading = this.$loading()
      try {
        for (let i = 0; i < files.length; i++) {
          let file = files[i]
          let message = this.validate(file)
          if (message) {
            event.preventDefault()
            loading.close()
            return this.$message.error(message)
          }
          const { data } = await Uploader.upload(file, '/files/upload')
          const params = {
            chatType:this.chatParams()?.chatType,
            chatUuid:this.chatParams()?.chatUuid,
            messageType,
            messageContent:{
              fileName:data.fileName,
              fileSize:data.size,
              url:data.ossUrl,
              fileId:data.id
            }
          }
          let messageInfo = await sendSingleMessage(params)
          this.$eventBus.$emit('addMsg_insideIM', messageInfo)
          this.$eventBus.$emit('updateCurrentChat', messageInfo)
          count++
          if (count >= files.length) loading.close()
        }
      } catch (error) {
        console.error('error', error);
        loading.close()
      }
    }
  },

}